package com.example.newsSys.listener;

import com.example.newsSys.constants.ListenerConstants;
import com.example.newsSys.constants.SessionConstants;
import jakarta.servlet.ServletContext;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class OnlineHttpSessionListener implements HttpSessionListener {
    // 如果用户不走寻常路，不正常退出清除user信息，那么在session过期后清除user信息
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String userAttribute = (String) session.getAttribute(SessionConstants.USER_SESSION); // getAttribute是获取的属性的value
        if (userAttribute != null) {
            // 如果当前session中有着user这样一个attribute则清除servletContext中的对应属性
            ServletContext context = session.getServletContext();
            List<String> onlineList = (List<String>) context.getAttribute(ListenerConstants.ONLINE_LIST);
            onlineList.remove(userAttribute);
        }
    }
}
